package ltd.newbee.mall.service.impl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.dao.GoodsSpecAttrMapper;
import ltd.newbee.mall.dao.GoodsSpecValueMapper;
import ltd.newbee.mall.entity.GoodsSpecAttr;
import ltd.newbee.mall.entity.GoodsSpecValue;
import ltd.newbee.mall.service.GoodsSpecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsSpecServiceImpl implements GoodsSpecService {

    @Autowired
    private GoodsSpecAttrMapper goodsSpecAttrMapper;
    @Autowired
    private GoodsSpecValueMapper goodsSpecValueMapper;



    @Override
    public List<GoodsSpecAttr> getAttrsByGoodsId(Long goodsId) {
        if (goodsId == null) {
            return new ArrayList<>();
        }
        try {
            List<GoodsSpecAttr> goodsSpecAttrs= goodsSpecAttrMapper.selectByGoodsId(goodsId);
            for (GoodsSpecAttr attr : goodsSpecAttrs) {
                // 3. 为每个属性获取对应的属性值列表
                List<GoodsSpecValue> values = goodsSpecValueMapper.selectByAttrId(attr.getId());
                attr.setGoodsSpecValues(values);
            }

            return goodsSpecAttrs;
        } catch (Exception e) {
            log.error("根据商品ID查询规格属性失败, goodsId: {}", goodsId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAttr(GoodsSpecAttr attr) {
        if (attr == null) {
            return false;
        }
        try {
            if (attr.getId() == null) {
                return goodsSpecAttrMapper.insert(attr) > 0;
            } else {
                return goodsSpecAttrMapper.updateByPrimaryKey(attr) > 0;
            }
        } catch (Exception e) {
            log.error("保存规格属性失败, attr: {}", attr, e);
            throw new RuntimeException("保存规格属性失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAttr(Integer id) {
        if (id == null) {
            return false;
        }
        try {
            goodsSpecValueMapper.deleteByAttrId(id.longValue());
            return goodsSpecAttrMapper.deleteByPrimaryKey(id) > 0;
        } catch (Exception e) {
            log.error("删除规格属性失败, id: {}", id, e);
            throw new RuntimeException("删除规格属性失败", e);
        }
    }

    @Override
    public List<GoodsSpecValue> getValuesByAttrId(Long attrId) {
        if (attrId == null) {
            return new ArrayList<>();
        }
        try {
            return goodsSpecValueMapper.selectByAttrId(attrId);
        } catch (Exception e) {
            log.error("根据属性ID查询属性值失败, attrId: {}", attrId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<GoodsSpecValue> getValuesByGoodsId(Long goodsId) {
        if (goodsId == null) {
            return new ArrayList<>();
        }
        try {
            return goodsSpecValueMapper.selectByGoodsId(goodsId);
        } catch (Exception e) {
            log.error("根据商品ID查询属性值失败, goodsId: {}", goodsId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveValue(GoodsSpecValue value) {
        if (value == null) {
            return false;
        }
        try {
            if (value.getId() == null) {
                return goodsSpecValueMapper.insert(value) > 0;
            } else {
                return goodsSpecValueMapper.updateByPrimaryKey(value) > 0;
            }
        } catch (Exception e) {
            log.error("保存属性值失败, value: {}", value, e);
            throw new RuntimeException("保存属性值失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteValue(Integer id) {
        if (id == null) {
            return false;
        }
        try {
            return goodsSpecValueMapper.deleteByPrimaryKey(id) > 0;
        } catch (Exception e) {
            log.error("删除属性值失败, id: {}", id, e);
            throw new RuntimeException("删除属性值失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSaveAttrs(List<GoodsSpecAttr> attrs) {
        if (CollectionUtils.isEmpty(attrs)) {
            return true;
        }
        try {
            for (GoodsSpecAttr attr : attrs) {
                saveAttr(attr);
            }
            return true;
        } catch (Exception e) {
            log.error("批量保存规格属性失败", e);
            throw new RuntimeException("批量保存规格属性失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSaveValues(List<GoodsSpecValue> values) {
        if (CollectionUtils.isEmpty(values)) {
            return true;
        }
        try {
            for (GoodsSpecValue value : values) {
                saveValue(value);
            }
            return true;
        } catch (Exception e) {
            log.error("批量保存属性值失败", e);
            throw new RuntimeException("批量保存属性值失败", e);
        }
    }

    @Override
    public Map<GoodsSpecAttr, List<GoodsSpecValue>> getFullSpecByGoodsId(Long goodsId) {
        if (goodsId == null) {
            return new HashMap<>();
        }
        try {
            List<GoodsSpecAttr> attrs = getAttrsByGoodsId(goodsId);
            Map<GoodsSpecAttr, List<GoodsSpecValue>> fullSpec = new HashMap<>();

            for (GoodsSpecAttr attr : attrs) {
                List<GoodsSpecValue> values = getValuesByAttrId(attr.getId().longValue());
                fullSpec.put(attr, values);
            }

            return fullSpec;
        } catch (Exception e) {
            log.error("获取商品完整规格信息失败, goodsId: {}", goodsId, e);
            return new HashMap<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAllByGoodsId(Long goodsId) {
        if (goodsId == null) {
            return false;
        }
        try {
            List<GoodsSpecAttr> attrs = getAttrsByGoodsId(goodsId);
            for (GoodsSpecAttr attr : attrs) {
                goodsSpecValueMapper.deleteByAttrId(attr.getId().longValue());
            }
            return goodsSpecAttrMapper.deleteByGoodsId(goodsId) > 0;
        } catch (Exception e) {
            log.error("删除商品所有规格信息失败, goodsId: {}", goodsId, e);
            throw new RuntimeException("删除商品规格信息失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copySpecToGoods(Long sourceGoodsId, Long targetGoodsId) {
        if (sourceGoodsId == null || targetGoodsId == null) {
            return false;
        }
        try {
            Map<GoodsSpecAttr, List<GoodsSpecValue>> sourceSpec = getFullSpecByGoodsId(sourceGoodsId);

            if (sourceSpec.isEmpty()) {
                return true;
            }

            Map<Integer, Integer> attrIdMap = new HashMap<>();

            for (GoodsSpecAttr sourceAttr : sourceSpec.keySet()) {
                GoodsSpecAttr targetAttr = new GoodsSpecAttr();
                targetAttr.setGoodsId(targetGoodsId);
                targetAttr.setAttrName(sourceAttr.getAttrName());
                targetAttr.setAttrKey(sourceAttr.getAttrKey());
                targetAttr.setSortOrder(sourceAttr.getSortOrder());

                goodsSpecAttrMapper.insert(targetAttr);

            }

            for (Map.Entry<GoodsSpecAttr, List<GoodsSpecValue>> entry : sourceSpec.entrySet()) {
                Integer newAttrId = attrIdMap.get(entry.getKey().getId());
                if (newAttrId != null) {
                    for (GoodsSpecValue sourceValue : entry.getValue()) {
                        GoodsSpecValue targetValue = new GoodsSpecValue();
                        targetValue.setAttrId(newAttrId.longValue());
                        targetValue.setValueName(sourceValue.getValueName());
                        targetValue.setValueData(sourceValue.getValueData());
                        targetValue.setSortOrder(sourceValue.getSortOrder());

                        goodsSpecValueMapper.insert(targetValue);
                    }
                }
            }

            return true;
        } catch (Exception e) {
            log.error("复制规格信息失败, sourceGoodsId: {}, targetGoodsId: {}", sourceGoodsId, targetGoodsId, e);
            throw new RuntimeException("复制规格信息失败", e);
        }
    }
}